package com.zgf.SingleList;

import com.zgf.lineTable.List;

/**
 * @author zgf
 * @date 2019/8/27 19:43
 */
public class SingleLinkedList implements List {

    Node head=new Node();
    int size;


    @Override
    public int size() {
        return size;
    }

    @Override
    public Object get(int i) {
        if (i<0 || i>size){
            throw new RuntimeException("数组越界异常："+i);
        }
        Node p=head;
        //p相当于指针  往后指
        for (int j=0;j<=i;j++){
            p=p.next;
        }
        return p.data;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void add(Object e) {
        this.add(size,e);
    }

    @Override
    public void add(int i, Object e) {
        if (i<0 || i>size){
            throw new RuntimeException("数组越界异常："+i);
        }
         Node p=head;
         Node newArray=new Node();
         newArray.data=e;
         for (int j=0;j<i;j++){
             p=p.next;
         }
         newArray.next=p.next;
         p.next=newArray;
         size++;
    }

    @Override
    public Object replace(int i, Object e) {
        Node p=head;
        for (int j=0;j<=i;j++){
            p=p.next;
        }
        p.data=e;
        return p.data;
    }

    @Override
    public Object remove(int i) {
        Node p=head;

        for (int j=0;j<i;j++){
            p=p.next;
        }
        p.next=p.next.next;
        size--;
        return p.next.data;
    }

    @Override
    public String toString() {
        Node p=head.next;
        if (size==0){
            return "[]";
        }
        StringBuilder builder=new StringBuilder("[");
        for (int i=0;i<size;i++){
            if (i==size-1){
                builder.append(p.data);
            }else{
                builder.append(p.data+",");
            }
            p=p.next;
        }
        builder.append("}");
        return builder.toString();
    }
}
